package org.jadelyre.core.worker;

import org.jadelyre.core.task.EntryQueue;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;

public class ScheduledWorker extends Worker<Schedule> {

    public ScheduledWorker(ThreadPoolExecutor executor, EntryQueue<Schedule> entryQueue) {
        super(executor, entryQueue, false);
    }

    @Override
    protected void execute() {
        ScheduledExecutorService service = (ScheduledExecutorService) executor;
        Schedule schedule = entryQueue.takeEntry();
        ScheduledFuture<?> future = null;
        switch (schedule.getType()) {
            case normal:
                executor.execute(schedule.getCommand());
                break;
            case schedule:
                future = service.schedule(schedule.getCommand(), schedule.getDelay(), schedule.getTimeUnit());
                break;
            case schedule_fix_rate:
                future = service.scheduleAtFixedRate(schedule.getCommand(), schedule.getInitialDelay(), schedule.getPeriod(), schedule.getTimeUnit());
                break;
            case schedule_fix_delay:
                future = service.scheduleWithFixedDelay(schedule.getCommand(), schedule.getInitialDelay(), schedule.getDelay(), schedule.getTimeUnit());
                break;
        }
        schedule.setFuture(future);
    }
}
